#py_social/networks/Gowalla.py
import urllib
import urlparse

from py_social.core import register_network
from py_social.core import Credential
from py_social.core import PySocialError
from py_social.core import BaseNetwork
from py_social import utils

@register_network
class Gowalla(BaseNetwork):
    name = 'ook'

    """This needs to stay updated"""
    scope_options = {
                     'post': 'publish_stream',
                     'get_friends': '',
                     'checkin': '',
                     'seprator': ',',
                     'default': 'offline_access',
    }
    """
    """
    domain = 'api.gowalla.com'
    auth_path = 'api/oauth/new'
    token_path = '/oauth/access_token'

    scope_str = ''

    def new_credential(self, request=None, code=''):
        """
        Take a callback request object and return a credential
        Currently handled request objects:
            Django
        Alternatively you can pass in the "code" given by facebook
        """
        if not code and not request:
            raise PySocialError("Either a request or a code must be supplied")
        if request:
            code = request.GET.get('code')
        if not code:
            raise PySocialError("Invalid code or request object")

        token_request_args = {'client_id' : self.pyso_client_id,
                          'client_secret': self.pyso_secret,
                          'redirect_uri': self.pyso_callback_url,
                          'code' : code}

        result = utils.makeAPICall(domain=self.domain,
                               apiHandler=self.token_path,
                               queryData=token_request_args,
                               secure=True, deserializeAs=None)

        ret = urlparse.parse_qs(result, keep_blank_values=False)

        access_token = ret['access_token'][0]

        ret = utils.makeAPICall(domain=self.domain,
                                apiHandler='me?access_token=%s' % access_token,
                                secure=True)

        cred_dict = {'network_name':self.pyso_name,
                     'access_token':access_token,
                     'uuid':ret['uuid'],
                     'name_in_network':ret['name_in_network'],
                     'scope_str':self.scope_str}

        return Credential(cred_dict)

    def get_auth_url(self, touch=False):
        arg_dict = {}
        arg_dict['client_id'] = self.pyso_client_id
        arg_dict['redirect_uri'] = self.pyso_callback_url
        arg_dict['scope'] = self.scope_str
        if touch:
            arg_dict['display'] = 'touch'
        args = urllib.urlencode(arg_dict)

        return '%s/%s?%s' % (self.domain, self.auth_path, args)

    def post(self, credential, message, **kwargs):
        pass
        #TODO

    def checkin(self, credentials, lng, lat, message=''):
        pass
        #TODO

    def get_friends(self, credentials):
        pass
        #TODO
